import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import {
  Button,
  message,
  DatePicker,
  Radio,
  Input,
  Select,
} from 'antd';
import React, { useState, useCallback, useRef, useEffect } from 'react';
import ProTable from '@ant-design/pro-table';
import { useRequest } from '@umijs/hooks';
import { irregularluggagesummaryTable, downloadluggagesummaryExcel,queryCityInfo} from '../service';
import moment from 'moment';
import styles from './index.less';
const { Option } = Select;
import AuthComponent from '@/components/Authorized/AuthComponent';

let hiddenData = null;
const TableList = (props) => {
  const [exportFlag, handleExportFlag] = useState('')
  const actionRef = useRef();
  const ref = useRef();
  const searchRef = useRef();

  const reloadTable = useCallback(function reloadData() {
    if (searchRef.current) {
      searchRef.current.click();
    }
  }, []);

  const [height, controlH] = useState(300);
  const [isCollapse, controlC] = useState(true);
  useEffect(() => {
    if (isCollapse) {
      controlH(document.body.clientHeight - 360);
    } else {
      controlH(document.body.clientHeight - 470);
    }
  }, [isCollapse])
  const columns = [
   {
    title: '航班日期',
    dataIndex: 'flightDate',
    width: 100,
    hideInSearch: true
    },
    {
      title: '航班开始日期',
      hideInTable: true,
      dataIndex: 'startDate',
      order: 7,
      renderFormItem: (_, { ...rest }) => {
        const format = 'YYYY-MM-DD';
        return (
          <DatePicker
            style={{width: '100%'}}
            format={format}
            {...rest}
          />
        );
      },
    },
    {
      title: '航班结束日期',
      hideInTable: true,
      order:6,
      dataIndex: 'endDate',
      renderFormItem: (_, { ...rest }) => {
        const format = 'YYYY-MM-DD';
        return (
          <DatePicker
            style={{width: '100%'}}
            format={format}
            {...rest}
          />
        );
      },
    },
    {
      title: '破损补偿',
      hideInSearch: true,
      dataIndex: 'damageCompensateCount',
      width: 100,
    },
    {
      title: '少收补偿',
      hideInSearch: true,
      dataIndex: 'lessCompensateCount',
      width: 100,
    },
    {
      title: '内件缺失补偿',
      hideInSearch: true,
      dataIndex: 'missCompensateCount',
      width: 100,
    },
    {
      title: '合计补偿',
      hideInSearch: true,
      dataIndex: 'totalCount',
      width: 100,
    }
  ];
  const [inited, setInited] = useState(false);
  const [firstLoadDate, setFirstLoadDate] = useState(true);
  useEffect(() => {
    if (actionRef.current && inited) {
       reloadTable();
    } else {
      setInited(true);
    }
  }, [inited]);

    // 切换清空搜索
    useEffect(() => {
      hiddenData = null
    // eslint-disable-next-line react-hooks/exhaustive-deps
    }, [])

  // 获取列表详情方法
  const beforeSearchSubmit = useCallback(params => {

    params['startDate'] = params.startDate ? params.startDate.format('YYYY-MM-DD') : '';
    params['endDate'] = params.endDate ? params.endDate.format('YYYY-MM-DD') : '';
     if (event&&event.target&&event.target.querySelector&&event.target.querySelector('span') && event.target.querySelector('span').innerText === '重 置') {
        ref.current.setFieldsValue({
          startDate: moment().subtract(1, 'days'),
          endDate: moment()
        })
      }
      return params
  }, []);

  const [searchParams, handleSearchParams] = useState() // 存储搜索条件
 
  //导出方法
  const handleExport = () => {
    if (!exportFlag){
      message.error('表格数据为空')
      return false
    }
    const hide = message.loading('正在导出');
    let res = downloadluggagesummaryExcel(searchParams)
      .then(res => {
        let blob = new Blob([res], {
          type:
            'application/vnd.ms-excel,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
        });
        let elink = document.createElement('a');
        let time=moment(Date.now()).format('YYYY-MM-DD HH_ss_mm')
        elink.download = '异常行李补偿合计表'+time+'.xls'
        elink.style.display = 'none';
        elink.href = URL.createObjectURL(blob);
        document.body.appendChild(elink);
        elink.click();
        document.body.removeChild(elink);
        hide();
        message.success('导出成功');
      })
      .catch(err => {
        console.log(err);
      });
  };

  return (
    <>
      <ProTable
        options={{density: false,fullScreen:true, reload:false, setting:true}}
        actionRef={actionRef}
        formRef={ref}
        dateFormatter="YYYY-MM-DD"
        scroll={{ x: 800, y: height }}
        size='small'
        search={{
          searchText: (
            <span ref={searchRef} href>
              查询
            </span>
          )
        }}
        toolBarRender={() => [
          <AuthComponent authCode="luggageCharts.totalCompensation.export">
             <Button icon="download" type="primary" onClick={handleExport} selectedKeys={[]} style={{ padding: '0px 0px 0px 8px',width:'73px' }}>
              导出           
            </Button>
          </AuthComponent>
        ]}
        beforeSearchSubmit={beforeSearchSubmit}
        headerTitle={
          <div>
            <span style={{ paddingRight: 10, fontWeight: "bold", color: "#000" }}>补偿合计表</span>
          </div>
        }
        request={params => {
          if (!params['startDate'] && !params['endState']&& firstLoadDate) {
            setFirstLoadDate(false)
            params['startDate'] = moment().subtract(1, 'days').format('YYYY-MM-DD');
            params['endDate'] = moment().format('YYYY-MM-DD');
            ref.current.setFieldsValue({
              startDate: moment().subtract(1, 'days')
            })
            ref.current.setFieldsValue({
              endDate: moment()
            })
          }
          handleSearchParams(params);
          return irregularluggagesummaryTable(params);
        }}
        postData={data => {
          if (data.length === 0) {
            handleExportFlag(false)
          } else {
            handleExportFlag(true)
          }
          return data
        }}
        columns={columns}
        rowKey="id"
        pagination={{
          showSizeChanger: true,
          showTotal: (total, range) => `${range[0]}-${range[1]} 共 ${total} 项`
        }}
      />
    </>
  );
};

export default Form.create()(TableList);
